
// Definition for a binary tree node.
function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}


/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function(root) {
  if(root == null) return '|N';
  let queue = [root], result = "";
  while(queue.length) {
    let node = queue[0];
    queue.splice(0, 1);
    if(node == null) {
      result += "|N";
      continue;
    } else {
      result += "|Y" + node.val;
    }
    if(node.left) queue.push(node.left);
    if(node.right) queue.push(node.right);
  }
  return result;
};

/**
 * Decodes your encoded data to tree.
 *
 * @param {string} data
 * @return {TreeNode}
 */
var deserialize = function(data) {
  let nodeList = [];
  let arr = data.split('|');
  for(let i = 0; i < arr.length; i++) {
    let node;
    if(arr[i] == 'N') {
      node = null;
    } else {
      let num = 0;
      num += parseInt(arr[i].split('').slice(1, arr[i].length).join(''));
      node = new TreeNode(num);
    }
    nodeList.push(node);
  }
  for(let i = 0; i < arr.length / 2; i++) {
    nodeList[i].left = nodeList[2 * i + 1];
    nodeList[i].right = nodeList[2 * i + 2];
  }
  return nodeList[0];
};

/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */
console.log(deserialize(serialize(root)));
